//
//
// 定义一个通信类
class Actions {
  private observers: Function[] = []
  private _chatRecord: {}[] = []

  constructor() {}

  set chatRecord(value: any) {
    this._chatRecord = value
    this.notifyObservers()
  }

  get chatRecord(): any {
    return this._chatRecord
  }

  addObserver(observer: Function) {
    this.observers.push(observer)
    console.log('已开始监听: ', observer)
  }

  removeObserver(observer: Function) {
    this.observers = this.observers.filter((obs) => obs !== observer)
    console.log('已取消监听: ', observer)
  }

  notifyObservers() {
    this.observers.forEach((observer) => observer(this._chatRecord))
  }

  setChatRecord(value: {}[]) {
    this.chatRecord = value
  }
}

//
//
// qiankun Actions通信
import { QiankunProps } from 'vite-plugin-qiankun/dist/helper'

let actions: QiankunProps

interface globalStateItf {
  userInfo: {
    id: string
    account: string
    avatar?: string
    nickname: string
  }
  currentChatRecord?: {}[]
}

// 乾坤全局状态
let globalState: globalStateItf

// 初始化一个 actions实例
const initActions = (a: QiankunProps) => {
  actions = a
  watchGlobalStateChange()
}

// 监听状态
const watchGlobalStateChange = () => {
  // 注册观察者函数
  // state: 变更后的状态; prev 变更前的状态
  // onGlobalStateChange 第二个参数为 true，表示立即执行一次观察者函数
  // @ts-ignore
  actions.onGlobalStateChange((state, prev) => {
    // console.log('Main application ', state, prev)
    globalState = { ...globalState, ...state }
    console.log('qiankun subApp action  globalState ', globalState)
  }, true)
}

// 获取全局状态
const getGlobalState = (): globalStateItf => globalState

export { initActions, actions as qiankunActions, getGlobalState }
